package com.mingmen.supplier.activity;


import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.util.TypedValue;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.ui.ImageGridActivity;
import com.lzy.imagepicker.view.CropImageView;
import com.mingmen.supplier.R;
import com.mingmen.supplier.base.BaseBean;
import com.mingmen.supplier.citypickerview.City2;
import com.mingmen.supplier.citypickerview.CityPicker;
import com.mingmen.supplier.citypickerview.Province2;
import com.mingmen.supplier.defineview.ClearEditText;
import com.mingmen.supplier.defineview.ClearEditText2;
import com.mingmen.supplier.defineview.GlideRoundTransform;
import com.mingmen.supplier.http.MyOkhttp;
import com.mingmen.supplier.http.callback.StringCallback;
import com.mingmen.supplier.httpconfig.AppConfig;
import com.mingmen.supplier.httpconfig.HttpResponse;
import com.mingmen.supplier.imageloader.GlideImageLoader;
import com.mingmen.supplier.immersionbar.ImmersionBar;
import com.mingmen.supplier.model.CityModel;
import com.mingmen.supplier.model.ListMarketModel;
import com.mingmen.supplier.model.MarkenModel;
import com.mingmen.supplier.model.PicSendModel;
import com.mingmen.supplier.model.SupplierDetailModel;
import com.mingmen.supplier.pickerview.OptionsPickerView;
import com.mingmen.supplier.util.GsonUtil;
import com.mingmen.supplier.util.Mobile;
import com.mingmen.supplier.util.SharePreferenceUtil;
import com.mingmen.supplier.util.ToastUtil;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Response;

public class SupplierDetailActivity extends AppCompatActivity {

    //返回按钮
    @BindView(R.id.text_return)
    TextView textReturn;
    //    中间按钮
    @BindView(R.id.text_center)
    TextView textCenter;
    private ImagePicker imagePicker;
    @BindView(R.id.img_zhengmian)
    ImageView img_zhengmian;
    @BindView(R.id.layout_shucai)
    LinearLayout layout_shucai;
    private int resurtResurant = 100;

    String verifyCode;
    @BindView(R.id.btn_login)
    Button btn_login;

    @BindView(R.id.text_SupplierName)
    ClearEditText text_SupplierName;
    @BindView(R.id.linkman)
    ClearEditText linkman;
    @BindView(R.id.tel)
    ClearEditText tel;
    //    categoryId 经营品类
    String categoryId = "";
    String markId = "";

    @BindView(R.id.address)
    ClearEditText address;


    String idPositive = "";
    String idReverse = "";
    String businessLicense = "";
    String circulationPermit = "";
    String foodPermit = "";

    String editPhone;
    @BindView(R.id.layout_market)
    LinearLayout layout_market;
    @BindView(R.id.linear_return)
    LinearLayout linear_return;
    @BindView(R.id.text_pinlei)
    TextView text_pinlei;
    @BindView(R.id.text_markId)
    TextView text_markId;
    @BindView(R.id.img_fanmian)
    ImageView img_fanmian;
    @BindView(R.id.img_yingye)
    ImageView img_yingye;


    String token;
    Context mContext;
    private CityPicker mCityPicker;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_supplier_detail);
        ButterKnife.bind(this);
        verifyCode = getIntent().getStringExtra("verifyCode");
        editPhone = getIntent().getStringExtra("editPhone");
        token = (String) SharePreferenceUtil.get(this, "token", "");
//        tel.setText(editPhone);
        ImmersionBar.with(this)
                .statusBarDarkFont(true, 0.2f)
                .init();
        mContext = this;
        createImagePicker();
        getListMarket();


//        s设置状态栏
        textCenter.setText("供应商基本信息");

    }

    public void getListMarket() {
        HttpResponse.listMarket(new StringCallback(this) {
            @Override
            public void onSuccess(String s, Call call, Response response) {
                Log.d("listMarket", s);
                List<Province2> mDatas = new ArrayList<>();
                Gson gson = new Gson();
                CityModel cityModel = new CityModel();
                cityModel = gson.fromJson(s, CityModel.class);

                List<String> reagion = new ArrayList<>();
                for (int i = 0; i < cityModel.getData().size(); i++) {
                    Province2 province2 = new Province2();
//            City2 city2
                    List<City2> city2List = new ArrayList<>();
                    for (int j = 0; j < cityModel.getData().get(i).getMarkets().size(); j++) {
                        City2 city2 = new City2();
                        city2.setId(cityModel.getData().get(i).getMarkets().get(j).getId());
                        city2.setName(cityModel.getData().get(i).getMarkets().get(j).getName());
                        Log.d("getName", cityModel.getData().get(i).getMarkets().get(j).getName());
                        city2List.add(city2);
//                province2.setMarkets(cityModel.getData().get(i).getMarkets());
                        province2.setMarkets(city2List);
                    }
                    province2.setRegion(cityModel.getData().get(i).getRegion());
                    mDatas.add(province2);
                }
                if (mCityPicker == null) {
                    mCityPicker = new CityPicker(SupplierDetailActivity.this, findViewById(R.id.layout_market), mDatas)
                            .setOnCitySelectListener(new CityPicker.OnCitySelectListener() {
                                @Override
                                public void onCitySelect(String province, String city, String county) {
//                                    Toast.makeText(StoreInformaticaActivity.this, province + city + county, Toast.LENGTH_SHORT).show();
                                    text_markId.setText(province + city);
//                            Log.d("optionsIds", optionsIds.get(options1).get(options2));
                                    markId = county;
                                }
                            });
                }


            }
        });
    }


    public void getData() {
        HttpResponse.getSupplier(token, new StringCallback(this) {
            @Override
            public void onSuccess(String s, Call call, Response response) {
                BaseBean baseBean = new BaseBean();
                baseBean = GsonUtil.GsonToBean(s, BaseBean.class);
                if (baseBean.getCode() == 0) {

                    SupplierDetailModel supplierDetailModel = new SupplierDetailModel();

                    supplierDetailModel = GsonUtil.GsonToBean(s, SupplierDetailModel.class);
                    text_SupplierName.setText(supplierDetailModel.getData().getSupplierName());
                    linkman.setText(supplierDetailModel.getData().getLinkman());
                    tel.setText(supplierDetailModel.getData().getTel());
                    text_pinlei.setText(supplierDetailModel.getData().getCategory());
                    text_markId.setText(supplierDetailModel.getData().getMarket());
                    address.setText(supplierDetailModel.getData().getAddress());
                    categoryId = supplierDetailModel.getData().getCategoryId();
                    markId = supplierDetailModel.getData().getMarketId();
                    idPositive = supplierDetailModel.getData().getIdPositive();
                    idReverse = supplierDetailModel.getData().getIdReverse();
                    businessLicense = supplierDetailModel.getData().getBusinessLicense();
                    circulationPermit = supplierDetailModel.getData().getCirculationPermit();
                    foodPermit = supplierDetailModel.getData().getFoodPermit();

                    Glide.with(mContext).load(AppConfig.IMGURL + supplierDetailModel.getData().getIdPositive()).dontAnimate().placeholder(R.mipmap.zhanwei).error(R.mipmap.zhanwei).transform(new GlideRoundTransform(mContext, 5)).into(img_zhengmian);
                    Glide.with(mContext).load(AppConfig.IMGURL + supplierDetailModel.getData().getIdReverse()).dontAnimate().placeholder(R.mipmap.zhanwei).error(R.mipmap.zhanwei).transform(new GlideRoundTransform(mContext, 5)).into(img_fanmian);
                    Glide.with(mContext).load(AppConfig.IMGURL + supplierDetailModel.getData().getBusinessLicense()).dontAnimate().placeholder(R.mipmap.zhanwei).error(R.mipmap.zhanwei).transform(new GlideRoundTransform(mContext, 5)).into(img_yingye);

                } else {
                    startActivity(new Intent(SupplierDetailActivity.this, LoginActivity.class));
                    Toast.makeText(SupplierDetailActivity.this, baseBean.getMessage() + "", Toast.LENGTH_SHORT).show();
                    finish();
                }

            }
        });
    }


    @OnClick({R.id.text_return, R.id.img_zhengmian, R.id.layout_shucai, R.id.btn_login, R.id.layout_market, R.id.linear_return, R.id.img_fanmian, R.id.img_yingye})
    public void onViewClicked(View view) {
        Intent intent;
        switch (view.getId()) {
            case R.id.text_return:
            case R.id.linear_return:
                finish();
                break;
            case R.id.img_zhengmian:
                photoflag = 0;
                intent = new Intent(this, ImageGridActivity.class);
                intent.putExtra(ImageGridActivity.EXTRAS_IMAGES, images);
                //ImagePicker.getInstance().setSelectedImages(images);
                startActivityForResult(intent, 100);
                break;
            case R.id.img_fanmian:
                photoflag = 1;
                intent = new Intent(this, ImageGridActivity.class);
                intent.putExtra(ImageGridActivity.EXTRAS_IMAGES, images);
                //ImagePicker.getInstance().setSelectedImages(images);
                startActivityForResult(intent, 100);
                break;
            case R.id.img_yingye:
                photoflag = 2;
                intent = new Intent(this, ImageGridActivity.class);
                intent.putExtra(ImageGridActivity.EXTRAS_IMAGES, images);
                //ImagePicker.getInstance().setSelectedImages(images);
                startActivityForResult(intent, 100);
                break;


            case R.id.layout_shucai:
                intent = new Intent(SupplierDetailActivity.this, SupplierDetailLabelActivity.class);
                intent.putExtra("text_pinlei", text_pinlei.getText().toString());
                intent.putExtra("flag", "1");
                startActivityForResult(intent, resurtResurant);
                break;
            case R.id.layout_market:
//                startActivityForResult(new Intent(StoreInformaticaActivity.this, StoreMarketLabelActivity.class), resurtMarket);
                mCityPicker.show();
                break;
            case R.id.btn_login:
                if (text_SupplierName.getText().toString().isEmpty()) {
                    Toast.makeText(this, "请输入供应商名称", Toast.LENGTH_SHORT).show();
                } else if (linkman.getText().toString().isEmpty()) {
                    Toast.makeText(this, "请输入联系人姓名", Toast.LENGTH_SHORT).show();
                } else if (tel.getText().toString().isEmpty()) {
                    Toast.makeText(this, "请输入手机号码", Toast.LENGTH_SHORT).show();
                } else if (!Mobile.isMobile(tel.getText().toString())) {
                    ToastUtil.showToast(this, "请输入正确手机号");
                }/* else if (categoryId.equals("")) {
                    Toast.makeText(this, "请选择经营品类", Toast.LENGTH_SHORT).show();
                } else if (markId.equals("")) {
                    Toast.makeText(this, "请选择经营品类", Toast.LENGTH_SHORT).show();
                } */ else if (address.getText().toString().isEmpty()) {
                    Toast.makeText(this, "请填写详细地址", Toast.LENGTH_SHORT).show();
                } else if (idPositive.equals("")) {
                    Toast.makeText(this, "请上传身份证正面照", Toast.LENGTH_SHORT).show();
                } else if (idReverse.equals("")) {
                    Toast.makeText(this, "请上传身份证背面照", Toast.LENGTH_SHORT).show();
                } else if (businessLicense.equals("")) {
                    Toast.makeText(this, "请上传营业执照", Toast.LENGTH_SHORT).show();
                } else if (circulationPermit.equals("")) {
                    Toast.makeText(this, "食品经营许可证", Toast.LENGTH_SHORT).show();
                }/* else if (foodPermit.equals("")) {
                    Toast.makeText(this, "食品生产许可证", Toast.LENGTH_SHORT).show();
                }*/ else {
                    HttpResponse.setSupplier(token, text_SupplierName.getText().toString(), linkman.getText().toString(), tel.getText().toString(), categoryId, markId, address.getText().toString(),
                            idPositive, idReverse, businessLicense, circulationPermit, foodPermit, text_pinlei.getText().toString(), text_markId.getText().toString(), new StringCallback(this) {
                                @Override
                                public void onSuccess(String s, Call call, Response response) {
                                    BaseBean baseBean = new BaseBean();
                                    baseBean = GsonUtil.GsonToBean(s, BaseBean.class);
                                    Toast.makeText(SupplierDetailActivity.this, baseBean.getMessage() + "", Toast.LENGTH_SHORT).show();
                                    finish();
                                }
                            }


                    );

                }

                break;

        }
    }

    public void createImagePicker() {
        imagePicker = ImagePicker.getInstance();

        imagePicker.setImageLoader(new GlideImageLoader());
        imagePicker.setMultiMode(false);
        imagePicker.setShowCamera(true);
        imagePicker.setCrop(false);
        imagePicker.setSaveRectangle(true);
        imagePicker.setStyle(CropImageView.Style.RECTANGLE);
//        Integer width = Integer.valueOf(280);
//        Integer height = Integer.valueOf(280);
        Integer width = Integer.valueOf(265);
        Integer height = Integer.valueOf(149);
        width = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, width, getResources().getDisplayMetrics());
        height = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, height, getResources().getDisplayMetrics());
        imagePicker.setFocusWidth(width);
        imagePicker.setFocusHeight(height);
//        imagePicker.setOutPutX(Integer.valueOf(800));
//        imagePicker.setOutPutY(Integer.valueOf(800));
        imagePicker.setOutPutX(Integer.valueOf(265));
        imagePicker.setOutPutY(Integer.valueOf(149));
    }

    ArrayList<ImageItem> images = null;
    String path;
    List<File> myfile = new ArrayList<>();
    File file;
    String companyName;
    String marketName;
    int photoflag = 0;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {
            if (data != null && requestCode == 100) {
                images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                for (int i = 0; i < images.size(); i++) {
                    Log.d("dkdkdkk", images.get(i).path);
                    path = images.get(i).path;
                    file = new File(path);
                    myfile.add(file);
                }
                Bitmap bm = BitmapFactory.decodeFile(images.get(0).path);
                MyOkhttp.post(AppConfig.IMGURL+"/system/upload/img")
//                MyOkhttp.post("http://192.168.3.18:9001/system/upload/img")
                        .params("token", token)
                        .addFileParams("file", myfile)
                        .execute(new StringCallback(this) {
                            @Override
                            public void onSuccess(String s, Call call, Response response) {
                                Log.d("DKkdkdkd", s);
                                PicSendModel picSendModel = new PicSendModel();
                                picSendModel = GsonUtil.GsonToBean(s, PicSendModel.class);

                                if (photoflag == 0) {
                                    idPositive = picSendModel.getData().get(0);
                                } else if (photoflag == 1) {
                                    idReverse = picSendModel.getData().get(0);
                                } else if (photoflag == 2) {
                                    businessLicense = picSendModel.getData().get(0);
                                } else if (photoflag == 3) {
                                    circulationPermit = picSendModel.getData().get(0);
                                } else if (photoflag == 4) {
                                    foodPermit = picSendModel.getData().get(0);
                                }

                            }
                        });

                if (photoflag == 0) {
                    img_zhengmian.setImageBitmap(bm);
                } else if (photoflag == 1) {
                    img_fanmian.setImageBitmap(bm);
                } else if (photoflag == 2) {
                    img_yingye.setImageBitmap(bm);
                } else if (photoflag == 4) {

                }
                myfile.clear();
                images.clear();
            } else {
                Toast.makeText(this, "没有数据", Toast.LENGTH_SHORT).show();
            }
        } else if (resultCode == resurtResurant) {

            categoryId = data.getStringExtra("categoryId");
            companyName = data.getStringExtra("companyName");

            String myName=companyName.replace(",","/");
//            text_pinlei.setText(companyName);
            text_pinlei.setText(myName);
            Log.d("categoryIdcategoryId", categoryId);
            Log.d("myNamemyName", myName);
        }
    }



}




